package com.macro.mall.portal.component;

import com.macro.mall.common.service.RedisService;
import com.macro.mall.portal.domain.wechat.AccessTokenResult;
import com.macro.mall.portal.service.WeChatService;
import com.macro.mall.portal.util.WeChatConstants;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @author：郎
 * @name：ScheduleTask
 * @date：2023/12/19 11:47
 */
@Component
@AllArgsConstructor
public class ScheduleTask {
    private final Logger LOGGER = LoggerFactory.getLogger(ScheduleTask.class);
    private final WeChatService weChatService;
    private final RedisService redisService;


    //    @Scheduled(cron = "0 0/5 * * * ?")
    @Scheduled(fixedRate = 5 * 60 * 1000, initialDelay = 0)
    public void refreshAccessToken() {
        Long expire = redisService.getExpire(WeChatConstants.REDIS_KEY_ACCESS_TOKEN);
        if (expire < 300) {
            if (expire == -2) {
                LOGGER.warn("小程序的accessToken 有效时间已不足，但续期失败,暂停5分钟,将再次续期。。。");
                return;
            }
            LOGGER.warn("小程序的accessToken 有效时间已不足，仅剩余：" + expire + " 秒,续期中。。。");
            AccessTokenResult accessTokenResult = weChatService.getAccessToken();
            LOGGER.warn("accessToken续期成功，当前有效时间为：" + accessTokenResult.getExpiresIn() + " 秒，accessToken值为：" + accessTokenResult.getAccessToken());
        }
    }
}
